import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios'

import{getMenuss} from'@/HTTPS/server'

export interface MenuItem {
  id: number;
  permissionName: string;
  permissionUrl: string;
  sort: number;
  parentId?: number | null;
  icon?: string;
  children?: MenuItem[];
}

export interface SavedCredentials {
  username: string;
  password: string;
}

export const useCounterStore = defineStore('counter', () => {
  const count = ref(0)
  const doubleCount = computed(() => count.value * 2)
  function increment() {
    count.value++
  }

  const use = reactive({
    userId: 0,
    roleId: 0,
    username: "",
    name: "",
    roleName: "",
  })

  // 存储记住的登录凭据
  const savedCredentials = ref<SavedCredentials | null>(null)

  // 保存登录凭据
  function saveCredentials(credentials: SavedCredentials) {
    savedCredentials.value = credentials
  }

  // 获取保存的登录凭据
  function getSavedCredentials(): SavedCredentials | null {
    return savedCredentials.value
  }

  // 清除保存的登录凭据
  function clearSavedCredentials() {
    savedCredentials.value = null
  }

   //菜单Model
  const menus =ref<any>([]);
  //动态加载菜单
  const getMenus=()=>{
    getMenuss({RoleId:use.roleId}).then((res:any)=>{
        menus.value =res.data.data;
        console.log(menus.value);
        return menus.value;
    })
  }

  // 用户菜单
  const userMenus = ref<MenuItem[]>([])

  // 加载用户菜单
  async function loadUserMenus() {
    if (use.userId > 0) {
      try {
        const response = await axios.get(`http://localhost:5125/api/User/GetUserMenus?userId=${use.userId}`)
        if (response.data.code === 200) {
          userMenus.value = response.data.data
        } else {
          console.error('加载菜单失败:', response.data.message)
        }
      } catch (error) {
        console.error('加载菜单异常:', error)
      }
    }
  }

  return { 
    count, 
    doubleCount, 
    increment, 
    use, 
    userMenus, 
    loadUserMenus,
    getMenus,
    menus,
    saveCredentials,
    getSavedCredentials,
    clearSavedCredentials
  }
}, { persist: true })
